package com.example.spider.provider.m3u8.handler.cryption;

import cn.hutool.core.util.StrUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

public class AesDecryptUtil {

    public static byte[] decrypt(byte[] cipherText, byte[] key, byte[] iv, String method) {
        if (StrUtil.isNotEmpty(method) && !method.contains("AES"))
            throw new RuntimeException("未知的算法！");
        // 判断Key是否正确
        if (key == null || key.length != 16)
            throw new RuntimeException("Key长度不是16位！");

        try {
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

            //如果m3u8有IV标签，那么IvParameterSpec构造函数就把IV标签后的内容转成字节数组传进去
            Cipher cipher;
            if (iv != null) {
                cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            } else {
                cipher = Cipher.getInstance("AES/ECB/NoPadding");
                iv = new byte[16];
            }

            AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
            return cipher.doFinal(cipherText, 0, cipherText.length);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
